﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Drawing;


[assembly: System.Web.UI.WebResource("RMS.Utils.Controls.Resources.PagingFirst.png", "img/png")]
[assembly: System.Web.UI.WebResource("RMS.Utils.Controls.Resources.PagingLast.png", "img/png")]
[assembly: System.Web.UI.WebResource("RMS.Utils.Controls.Resources.PagingNext.png", "img/png")]
[assembly: System.Web.UI.WebResource("RMS.Utils.Controls.Resources.PagingPrevious.png", "img/png")]

namespace RMS.Utils.Controls
{
    /// <summary>
    /// Summary description for DataPager
    /// </summary>
    /// 
    [ToolboxData("<{0}:DataPager runat=server />")]
    public class DataPager : WebControl
    {
        #region [Controls]
        private readonly Label lblTotalPage;
        private readonly Label lblTotalRecord;
        private readonly Label lblPageError;
        private readonly ImageButton btnMoveFirst;
        private readonly ImageButton btnMovePrevious;
        private readonly ImageButton btnMoveNext;
        private readonly ImageButton btnMoveLast;
        private readonly TextBox txtPage;
        private readonly DropDownList ddlRecords;
        #endregion

        #region [Properties]

        [Category("Action")]
        public event EventHandler PageIndexChange;

        [Bindable(true), Category("Behavior"), Description("Total number of records"), DefaultValue(0), Localizable(true)]
        public int TotalRecords
        {
            get
            {
                int totalRecords = (int)this.ViewState["TotalRecords"];
                if (totalRecords != 0)
                {
                    return totalRecords;
                }
                return 0;
            }
            set
            {
                this.ViewState["TotalRecords"] = value;
            }
        }
        [Bindable(true), Category("Behavior"), Description("Current page index"), DefaultValue(1), Localizable(true)]
        public int PageIndex
        {
            get
            {
                int pageIndex = (int)this.ViewState["PageIndex"];
                if (pageIndex != 0)
                {
                    return pageIndex;
                }
                return 1;
            }
            set
            {
                this.ViewState["PageIndex"] = value;
            }
        }
        [Bindable(true), Category("Behavior"), Description("Total number of records to each page"),
        DefaultValue(25), Localizable(true)]
        public int RecordsPerPage
        {
            get
            {
                int recordsPerPage = (int)this.ViewState["RecordsPerPage"];
                if (recordsPerPage != 0)
                {
                    return recordsPerPage;
                }
                return 25;
            }
            set
            {
                this.ViewState["RecordsPerPage"] = value;
            }

        }
        private decimal TotalPages
        {
            get
            {
                decimal totalPages = (decimal)this.ViewState["TotalPages"];
                if (totalPages != 0)
                {
                    return totalPages;
                }
                return 0;
            }
            set
            {
                this.ViewState["TotalPages"] = value;
            }
        }
        public int CurrentStartRow
        {
            get
            {
              return  ((PageIndex - 1) * RecordsPerPage) + 1;
            }
        }

        #endregion

        #region [Constructor]
        public DataPager()
            : base(HtmlTextWriterTag.Div)
        {
            lblTotalPage = new Label();
            lblTotalRecord = new Label();
            lblPageError = new Label();
            btnMoveFirst = new ImageButton();
            btnMoveLast = new ImageButton();
            btnMoveNext = new ImageButton();
            btnMovePrevious = new ImageButton();
            txtPage = new TextBox();
            ddlRecords = new DropDownList();

        }
        #endregion

        #region [Event]
        protected virtual void OnPageIndexChange(EventArgs e)
        {
            if (PageIndexChange != null)
            {
                PageIndexChange(this, e);
            }
        }

        #endregion

        #region [Override Methods]
        protected override void OnInit(EventArgs e)
        {
            this.controlsInitialization();
            this.chiledControlDesign();
            base.OnInit(e);
            Page.RegisterRequiresControlState(this);
        }
        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.RecordsPerPage = Convert.ToInt32(ddlRecords.Text);
                this.updatePaging();
            }
        }
        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
        }
        #endregion

        #region [Control Events]
        protected void btnMove_Click(object sender, CommandEventArgs e)
        {
            switch (Convert.ToString(e.CommandArgument))
            {
                case "First":
                    this.PageIndex = 1;
                    break;
                case "Previous":
                    this.PageIndex--;
                    break;
                case "Next":
                    this.PageIndex++;
                    break;
                case "Last":
                    this.PageIndex = (int)this.TotalPages;
                    break;
            }
            this.updatePaging();
        }
        protected void txtPage_TextChanged(object sender, EventArgs e)
        {
            try
            {
                lblPageError.Visible = false;
                int newPage = Convert.ToInt32(((TextBox)sender).Text);
                if (newPage < 0)
                {
                    throw new Exception();
                }
                if (newPage > this.TotalPages)
                    this.PageIndex = (int)this.TotalPages;
                else
                    this.PageIndex = newPage;
                this.updatePaging();
            }
            catch (Exception)
            {
                lblPageError.Visible = true;
            }
        }
        protected void ddlRecords_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.RecordsPerPage = Convert.ToInt32(ddlRecords.Text);
            this.PageIndex = 1;
            this.updatePaging();
        }
        #endregion

        #region [Helper Methods]
        private void updatePaging()
        {
            if (TotalRecords > 0)
            {
                this.OnPageIndexChange(EventArgs.Empty);
                lblTotalRecord.ForeColor = Color.Black;
                ddlRecords.Enabled = true;
                int currentEndRow = (PageIndex * RecordsPerPage);
                if (currentEndRow > TotalRecords) currentEndRow = TotalRecords;

                if (currentEndRow < RecordsPerPage) RecordsPerPage = currentEndRow;

                this.TotalPages = Math.Ceiling((decimal)TotalRecords / RecordsPerPage);
                txtPage.Text = string.Format("{0:00}", this.PageIndex);
                lblTotalRecord.Text = string.Format("{0:00}-{1:00} of {2:00} record(s)", CurrentStartRow, currentEndRow, TotalRecords);
                lblTotalPage.Text = string.Format(" of {0:00} page(s)", this.TotalPages);

                btnMoveFirst.Enabled = (PageIndex == 1) ? false : true;
                btnMovePrevious.Enabled = (PageIndex > 1) ? true : false;
                btnMoveNext.Enabled = (PageIndex * RecordsPerPage < TotalRecords) ? true : false;
                btnMoveLast.Enabled = (PageIndex * RecordsPerPage >= TotalRecords) ? false : true;
            }
            else
            {
                lblTotalPage.Text = "";
                lblTotalRecord.Text = "No Record Found!";
                lblTotalRecord.ForeColor = Color.Red;
                btnMoveFirst.Enabled = false;
                btnMovePrevious.Enabled = false;
                btnMoveNext.Enabled = false;
                btnMoveLast.Enabled = false;
                txtPage.Enabled = false;
                ddlRecords.Enabled = false;
            }
        }
        private void chiledControlDesign()
        {
            Controls.Clear();

            Table table = new Table();
            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            Table subTable = new Table();
            TableRow subRow = new TableRow();
            TableCell subCell = new TableCell();

            table.CellSpacing = 0;
            table.CellPadding = 0;
            table.CssClass = this.CssClass;
            table.HorizontalAlign = HorizontalAlign.Center;

            row.CssClass = "GridFooter";

            cell.Controls.Add(lblTotalRecord);
            row.Cells.Add(cell);
            //_________________________________________________________________
            cell = new TableCell();
            subCell.Controls.Add(btnMoveFirst);
            subRow.Cells.Add(subCell);
            subCell = new TableCell();
            subCell.Controls.Add(btnMovePrevious);
            subRow.Cells.Add(subCell);
            subCell = new TableCell();
            subCell.Controls.Add(txtPage);
            subRow.Cells.Add(subCell);
            subCell = new TableCell();
            subCell.Controls.Add(lblTotalPage);
            subRow.Cells.Add(subCell);
            subCell = new TableCell();
            subCell.Controls.Add(btnMoveNext);
            subRow.Cells.Add(subCell);
            subCell = new TableCell();
            subCell.Controls.Add(btnMoveLast);
            subRow.Cells.Add(subCell);
            subCell = new TableCell();
            subTable.Rows.Add(subRow);
            cell.Controls.Add(subTable);
            row.Cells.Add(cell);
            //______________________________________________________________________
            cell = new TableCell();
            cell.Controls.Add(ddlRecords);
            row.Cells.Add(cell);
            table.Rows.Add(row);

            cell = new TableCell();
            cell.Controls.Add(lblPageError);
            row = new TableRow();
            row.Cells.Add(cell);
            table.Rows.Add(row);

            Controls.Add(table);
        }
        private void controlsInitialization()
        {
            lblTotalPage.ID = "lblTotalPage";

            lblTotalRecord.ID = "lblTotalRecord";

            lblPageError.Text = "Inviled Page Number";
            lblPageError.ForeColor = Color.Red;
            lblPageError.ID = "lblPageError";
            lblPageError.Visible = false;

            btnMoveFirst.Command += new CommandEventHandler(btnMove_Click);
            btnMoveFirst.CommandArgument = "First";
            btnMoveFirst.ID = "btnMoveFirst";
            btnMoveFirst.ImageUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), @"RMS.Utils.Controls.Resources.PagingFirst.png");

            btnMoveLast.Command += new CommandEventHandler(btnMove_Click);
            btnMoveLast.CommandArgument = "Last";
            btnMoveLast.ID = "btnMoveLast";
            btnMoveLast.ImageUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), @"RMS.Utils.Controls.Resources.PagingLast.png");

            btnMoveNext.Command += new CommandEventHandler(btnMove_Click);
            btnMoveNext.CommandArgument = "Next";
            btnMoveNext.ID = "btnMoveNext";
            btnMoveNext.ImageUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), @"RMS.Utils.Controls.Resources.PagingNext.png");

            btnMovePrevious.Command += new CommandEventHandler(btnMove_Click);
            btnMovePrevious.CommandArgument = "Previous";
            btnMovePrevious.ID = "btnMovePrevious";
            btnMovePrevious.ImageUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), @"RMS.Utils.Controls.Resources.PagingPrevious.png");

            txtPage.TextChanged += new EventHandler(txtPage_TextChanged);
            txtPage.AutoPostBack = true;
            txtPage.ID = "txtPage";

            ddlRecords.SelectedIndexChanged += new EventHandler(ddlRecords_SelectedIndexChanged);
            ddlRecords.AutoPostBack = true;
            ddlRecords.ID = "ddlRecords";
            int[] Paging = { 10, 20, 30, 50, 100 };
            for (int p = 0; p < Paging.Length; p++)
            {
                ddlRecords.Items.Add(Paging[p].ToString());
                ddlRecords.SelectedIndex = 0;
            }
        }
        #endregion
    }
}